﻿using System;

namespace ControleRepresentanteSync.Application.Wizard
{
    internal class CompositeWizardPageProvider : IWizardPageProvider
    {
        private readonly IWizardPageProvider[] m_WizardPageProviders;
        private int m_Index;

        public CompositeWizardPageProvider(params IWizardPageProvider[] wizardPageProviders)
        {
            m_WizardPageProviders = wizardPageProviders;
            m_Index = 0;

            foreach (IWizardPageProvider wizardPageProvider in wizardPageProviders)
            {
                wizardPageProvider.Changed += WizardPageProviderChanged;
            }
        }

        private void WizardPageProviderChanged(object sender, EventArgs e)
        {
            if (Changed != null)
                Changed(this, EventArgs.Empty);
        }

        public IWizardPageViewModel Current { get { return m_WizardPageProviders[m_Index].Current; } }
        public bool CanGoBack { get { return m_WizardPageProviders[m_Index].CanGoBack || m_Index > 0; } }
        public bool IsFinish { get { return m_WizardPageProviders[m_Index].IsFinish && m_Index == m_WizardPageProviders.Length - 1; } }

        public IWizardPageViewModel MoveNext()
        {
            return m_WizardPageProviders[m_Index].IsFinish 
                ? m_WizardPageProviders[++m_Index].Current 
                : m_WizardPageProviders[m_Index].MoveNext();
        }

        public IWizardPageViewModel MoveBack()
        {
            return m_WizardPageProviders[m_Index].CanGoBack 
                ? m_WizardPageProviders[m_Index].MoveBack()
                : m_WizardPageProviders[--m_Index].Current;
        }

        public event EventHandler Changed;

        public void Dispose()
        {
            foreach (IWizardPageProvider wizardPageProvider in m_WizardPageProviders)
            {
                wizardPageProvider.Changed -= WizardPageProviderChanged;
                wizardPageProvider.Dispose();
            }
        }
    }
}